<template>
    <div class="Box">
      <!-- 顶部搜索 -->
      <div class="SearchBox flex-LAR">
        <el-input v-model="SearchKeyWord.searchValue" placeholder="请输入搜索内容" class="input-with-select">
          <template #prepend>
            <el-select v-model="SearchKeyWord.selectKey" style="width: 6.25rem">
              <el-option label="公告标题" value="title" />
              <el-option label="发布人" value="publisher" />
            </el-select>
          </template>
          <template #append>
            <el-button class="searchBtn" :icon="Search" />
          </template>
        </el-input>
        <div>
          <el-button type="success" @click="handleAdd">发布公告</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <div class="TableBox">
        <cy-table class="Table" row-key="id" :data="tableData" :columns="ruleTable.columns" :loading="loading" />
      </div>
      <!-- 分页 -->
      <div class="PageBox">
        <el-pagination :hide-on-single-page="true" v-model:current-page="page.currentPage" v-model:page-size="page.pageSize"
          v-model:total="page.total" />
      </div>
  
      <!-- 新增/编辑弹窗 -->
      <el-dialog v-model="dialogVisible" :title="dialogTitle" width="70%">
        <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="公告标题" prop="title">
                <el-input v-model="form.title" placeholder="请输入公告标题" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="公告类型" prop="type">
                <el-select v-model="form.type" placeholder="请选择公告类型">
                  <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="发布时间" prop="publish_time">
                <el-date-picker v-model="form.publish_time" type="datetime" placeholder="选择日期时间" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发布人" prop="publisher">
                <el-input v-model="form.publisher" placeholder="请输入发布人" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="封面图片" prop="cover_image">
                <el-upload
                  action="#"
                  list-type="picture-card"
                  :auto-upload="false"
                  :on-change="handleCoverChange"
                  :file-list="coverFileList"
                >
                  <el-icon><Plus /></el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-form-item label="公告内容" prop="content">
            <el-input v-model="form.content" type="textarea" :rows="6" placeholder="请输入公告内容" />
          </el-form-item>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="是否置顶" prop="is_top">
                <el-switch v-model="form.is_top" active-text="是" inactive-text="否" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择状态">
                  <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
  
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script lang="tsx" setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search, Plus } from "@element-plus/icons-vue";
  import CyTable from "@/components/table";
  
  const page = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
  });
  
  const SearchKeyWord = reactive({
    selectKey: "title",
    searchValue: "",
  });
  
  const tableData = ref([
    {
      id: 1,
      title: '关于社区垃圾分类的温馨提示',
      type: 'notice',
      publish_time: '2023-05-10 09:00:00',
      publisher: '物业办公室',
      cover_image: 'https://example.com/cover1.jpg',
      content: '尊敬的业主：为进一步推进垃圾分类工作，请各位业主按照垃圾分类标准投放垃圾...',
      is_top: true,
      status: 'published',
      view_count: 256,
      created_at: '2023-05-08',
    },
    {
      id: 2,
      title: '社区停水通知',
      type: 'notification',
      publish_time: '2023-06-15 14:30:00',
      publisher: '物业工程部',
      cover_image: '',
      content: '因供水管道维修，6月16日9:00-17:00社区将暂停供水，请提前储水...',
      is_top: false,
      status: 'published',
      view_count: 532,
      created_at: '2023-06-14',
    },
    {
      id: 3,
      title: '社区中秋晚会活动预告',
      type: 'activity',
      publish_time: '2023-09-20 10:00:00',
      publisher: '社区居委会',
      cover_image: 'https://example.com/cover3.jpg',
      content: '为庆祝中秋佳节，社区将于9月29日晚7点在中心广场举办中秋晚会...',
      is_top: true,
      status: 'published',
      view_count: 189,
      created_at: '2023-09-19',
    },
    {
      id: 4,
      title: '消防安全知识讲座通知',
      type: 'education',
      publish_time: '2023-07-05 13:00:00',
      publisher: '社区安全办',
      cover_image: 'https://example.com/cover4.jpg',
      content: '为提高居民消防安全意识，社区将于7月10日下午2点在会议室举办消防安全知识讲座...',
      is_top: false,
      status: 'draft',
      view_count: 0,
      created_at: '2023-07-03',
    },
    {
      id: 5,
      title: '关于电动车充电安全的温馨提示',
      type: 'notice',
      publish_time: '2023-08-12 11:00:00',
      publisher: '物业安全部',
      cover_image: '',
      content: '近期发现部分业主在楼道内为电动车充电，存在严重安全隐患...',
      is_top: false,
      status: 'published',
      view_count: 321,
      created_at: '2023-08-10',
    }
  ]);
  
  const dialogVisible = ref(false);
  const dialogTitle = ref('');
  const formRef = ref(null);
  const coverFileList = ref([]);
  
  const form = reactive({
    id: '',
    title: '',
    type: '',
    publish_time: '',
    publisher: '',
    cover_image: '',
    content: '',
    is_top: false,
    status: ''
  });
  
  const rules = reactive({
    title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
    type: [{ required: true, message: '请选择公告类型', trigger: 'change' }],
    publish_time: [{ required: true, message: '请选择发布时间', trigger: 'change' }],
    publisher: [{ required: true, message: '请输入发布人', trigger: 'blur' }],
    content: [{ required: true, message: '请输入公告内容', trigger: 'blur' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  });
  
  const typeOptions = ref([
    { value: 'notice', label: '通知公告' },
    { value: 'notification', label: '物业通知' },
    { value: 'activity', label: '社区活动' },
    { value: 'education', label: '宣传教育' },
    { value: 'policy', label: '政策法规' }
  ]);
  
  const statusOptions = ref([
    { value: 'draft', label: '草稿' },
    { value: 'published', label: '已发布' },
    { value: 'archived', label: '已归档' }
  ]);
  
  const ruleTable = reactive({
    columns: [
      { prop: "id", label: "公告ID" },
      { prop: "title", label: "公告标题" },
      {
        prop: "type", label: "公告类型",
        render: ({ row }) => (
          <el-tag type={getTypeTag(row.type)}>
            {getTypeName(row.type)}
          </el-tag>
        ),
      },
      { prop: "publish_time", label: "发布时间" },
      { prop: "publisher", label: "发布人" },
      { prop: "view_count", label: "浏览次数" },
      {
        prop: "is_top", label: "是否置顶",
        render: ({ row }) => (
          <el-tag type={row.is_top ? 'success' : 'info'}>
            {row.is_top ? '是' : '否'}
          </el-tag>
        ),
      },
      {
        prop: "status", label: "状态",
        render: ({ row }) => (
          <el-tag type={getStatusTag(row.status)}>
            {getStatusName(row.status)}
          </el-tag>
        ),
      },
      {
        label: "操作",
        align: "center",
        width: 250,
        render: ({ row }) => (
          <div>
            <el-button>查看</el-button>
            <el-button type="primary" onClick={() => handleEdit(row)}>编辑</el-button>
            <el-button type="danger" onClick={() => handleDelete(row.id)}>删除</el-button>
          </div>
        ),
      },
    ],
  });
  
  const getTypeName = (type) => {
    const item = typeOptions.value.find(item => item.value === type);
    return item ? item.label : '未知';
  };
  
  const getTypeTag = (type) => {
    const map = {
      notice: '',
      notification: 'info',
      activity: 'warning',
      education: 'success',
      policy: 'danger'
    };
    return map[type] || '';
  };
  
  const getStatusName = (status) => {
    const item = statusOptions.value.find(item => item.value === status);
    return item ? item.label : '未知';
  };
  
  const getStatusTag = (status) => {
    const map = {
      draft: 'info',
      published: 'success',
      archived: 'warning'
    };
    return map[status] || '';
  };
  
  const handleAdd = () => {
    dialogTitle.value = '发布新公告';
    formRef.value?.resetFields();
    form.id = '';
    form.is_top = false;
    coverFileList.value = [];
    dialogVisible.value = true;
  };
  
  const handleEdit = (row) => {
    dialogTitle.value = '编辑公告';
    Object.assign(form, row);
    if (row.cover_image) {
      coverFileList.value = [{ name: '封面图片', url: row.cover_image }];
    } else {
      coverFileList.value = [];
    }
    dialogVisible.value = true;
  };
  
  const handleDelete = (id) => {
    ElMessageBox.confirm('确定要删除这条公告吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      tableData.value = tableData.value.filter(item => item.id !== id);
      ElMessage.success('删除成功');
    }).catch(() => {
      ElMessage.info('已取消删除');
    });
  };
  
  const handleCoverChange = (file) => {
    coverFileList.value = [file];
    form.cover_image = URL.createObjectURL(file.raw);
  };
  
  const submitForm = () => {
    formRef.value.validate((valid) => {
      if (valid) {
        if (form.id) {
          // 编辑
          const index = tableData.value.findIndex(item => item.id === form.id);
          if (index !== -1) {
            tableData.value[index] = { ...form };
            ElMessage.success('编辑成功');
          }
        } else {
          // 新增
          form.id = tableData.value.length + 1;
          form.view_count = 0;
          form.created_at = new Date().toISOString().split('T')[0];
          tableData.value.unshift({ ...form });
          ElMessage.success('发布成功');
        }
        dialogVisible.value = false;
      } else {
        ElMessage.error('表单验证失败');
      }
    });
  };
  </script>
  
  <style scoped lang="scss">
  .Box {
    position: relative;
  
    .SearchBox {
      width: 100%;
      height: 60px;
      background-color: #fff;
      border-bottom: 1px solid #eee;
  
      .el-input {
        width: 350px;
        margin-left: 0.5rem;
      }
  
      .searchBtn {
        color: rgb(15, 153, 245);
      }
  
      .addBtn {
        margin-right: 1rem;
      }
    }
  
    .PageBox {
      background-color: #fff;
      padding-left: 30%;
      margin: 1rem;
    }
  
    .TableBox {
      .Table {
        width: 100%;
        min-height: 25rem;
        border-top: 1px solid #eee;
      }
    }
  
    .EditForm {
      :deep(.el-form-item__content) {
        display: flex;
        justify-content: center;
        align-content: center;
      }
    }
  }
  </style>